﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SCRUM.Core.BusinessObjects;
using System.Data.Common;

namespace SCRUM.Core.DataProviders
{
    /// <summary>
    /// Privider for comunication with the database
    /// </summary>
    public partial class DBDataProvider : DataProvider
	{
		/// <summary>
		/// Gets the settings for user.
		/// </summary>
		/// <param name="userID">The user ID.</param>
		/// <returns>
		/// User settings for user with specified ID.
		/// </returns>
		public override UserSettings GetSettingsForUser(int userID)
		{
			UserSettings us = null;
			try
			{
				connection.Open();

				DbParameter dbUserID = CreateParameter("userID", userID);

				DbDataReader data = GetGrid("userSettings/GetSettingsForUser", dbUserID);

				if (data.Read())
				{
					us = new UserSettings(
							(int)data["ID"],
							(string)data["LANGUAGE"],
							(string)data["THEME"],
                            (bool)data["MAIL_TASK_ASSIGNMENT"],
                            (bool)data["MAIL_TASK_STATE"]);
				}
			}
			finally
			{
				connection.Close();
			}
			return us;
		}

		/// <summary>
		/// Creates the default settings.
		/// </summary>
		/// <param name="userID">The user ID.</param>
		public override void CreateDefaultSettings(int userID)
		{
            DbParameter dbuserID = CreateParameter("userID", userID);

            try
            {
                connection.Open();
                ExecuteNonQuery("userSettings/CreateDefaultSettings", dbuserID);

            }
            finally
            {
                connection.Close();
            }
		}

		/// <summary>
		/// Updates the settings for logged user.
		/// </summary>
		/// <param name="userID">The user ID.</param>
		/// <param name="us">The user settings.</param>
		public override void UpdateSettingsForLoggedUser(int userID, UserSettings us)
		{
			try
			{
				connection.Open();

				DbParameter dbUserID = CreateParameter("userID", userID);
				DbParameter dbLanguage = CreateParameter("language", us.Language);
				DbParameter dbTheme = CreateParameter("theme", us.Theme);
                DbParameter dbMailAssignment = CreateParameter("taskAssignment", us.MailTaskAssignment);
                DbParameter dbMailState = CreateParameter("taskState", us.MailTaskState);

				int result = ExecuteNonQuery("userSettings/UpdateSettingsForLoggedUser", dbUserID, dbLanguage, dbTheme, dbMailAssignment, dbMailState);
                if (result != 1)
                {
                    throw new Exceptions.Database.InconsistentDatabaseException();
                }
            }
			finally
			{
				connection.Close();
			}
		}
	}
}
